home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / msoftapp.zip / SORT.CPP < prev    next >
C/C++ Source or Header  |  1993-06-01  |  1KB  |  64 lines

  1. ////////////////////////////////////////////////////////////////
  2. // Sort program showing how to use qsort with C++.
  3. //
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <iostream.h>
  8.  
  9. //////////////////
  10. // Your favorite class that you want to sort.
  11. //
  12. class Person {
  13.     char name[20];
  14. public:
  15.     Person(const char *n) { strcpy(name, n); }
  16.     void print()    { cout << name << '\n'; };
  17.  
  18.     // Note that Compare function is static
  19.     static int Compare(const void* v1, const void* v2);
  20. };
  21.  
  22. /////////////////
  23. // Static sort function can access name since its a class member.
  24. // But it's an ordinary function; there's no "this" pointer.
  25. // 
  26. int Person::Compare(const void* v1, const void* v2)
  27. {
  28.     Person *p1 = *((Person**)v1);
  29.     Person *p2 = *((Person**)v2);
  30.     return strcmp(p1->name, p2->name);
  31. }
  32.  
  33. // Some sample people (unsorted).
  34. Person people[] = {
  35.     { "Cynthia" },
  36.     { "Sandy" },
  37.     { "Carl" },
  38.     { "Alfred" },
  39.     { "Beth" }
  40. };
  41. const NPEOPLE = sizeof(people)/sizeof(Person);
  42.  
  43. /////////////////
  44. // Main program loop: 
  45. // create array of pointers, sort it, then print.
  46. // 
  47. main(int, char**)
  48. {
  49.     Person *array[NPEOPLE];
  50.  
  51.     // Initialize array of pointers from sample Persons
  52.     for (int i=0; i<NPEOPLE; i++)
  53.         array[i] = &people[i];
  54.  
  55.     // sort the array
  56.     qsort(array, NPEOPLE, sizeof(Person*), Person::Compare);
  57.  
  58.     // print
  59.     for (i=0; i<NPEOPLE; i++)
  60.         array[i]->print();
  61.  
  62.     return 0;
  63. }
  64.